package com.wayne.oauth2.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wayne.oauth2.entity.GranterUser;
import com.wayne.oauth2.entity.Role;
import com.wayne.oauth2.entity.UserAuth;
import com.wayne.oauth2.entity.UserInfo;
import com.wayne.oauth2.mapper.UserAuthMapper;
import com.wayne.oauth2.mapper.UserInfoMapper;
import com.wayne.oauth2.service.GranterLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

@Service
public class GranterLoginServiceImpl implements GranterLoginService {
    //邮箱密码登录
    private final String EMAIL_CODE_TYPE = "02";
    @Autowired
    private UserAuthMapper userAuthMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 实现邮箱和密码登录
     *
     * @param identifier
     * @param credential
     * @return
     */
    @Override
    public GranterUser loadByEmailPassword(String identifier, String credential) {
        QueryWrapper<UserAuth> queryWrapper = new QueryWrapper<UserAuth>();
        queryWrapper.lambda().eq(UserAuth::getIdentityType, EMAIL_CODE_TYPE)
                .eq(UserAuth::getIdentifier, identifier);
        UserAuth userAuth = userAuthMapper.selectOne(queryWrapper);
        if (userAuth == null) {
            throw new UsernameNotFoundException("账号不存在");
        }
        //校验密码
        boolean flag = passwordEncoder.matches(credential, userAuth.getCredential());
        if (flag) {
            //获取用户信息
            QueryWrapper<UserInfo> userInfoQW = new QueryWrapper<>();
            userInfoQW.lambda().eq(UserInfo::getAuthId, userAuth.getAuthId());
            UserInfo userInfo = userInfoMapper.selectOne(userInfoQW);
            if (userInfo == null) {
                throw new UsernameNotFoundException("账号未关联用户信息");
            }
            //获取权限信息
            List<Role> roles = userInfoMapper.selectRoles(userInfo.getUserId());
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            roles.forEach(role -> authorities.add(new SimpleGrantedAuthority(role.getRoleName().toUpperCase(Locale.ROOT))));
            GranterUser granterUser = new GranterUser();
            granterUser.setAvatar(userInfo.getAvatar());
            granterUser.setMobile(userInfo.getMobile());
            granterUser.setNickName(userInfo.getNickName());
            granterUser.setAuthorities(authorities);
            return granterUser;
        } else
            return new GranterUser();
    }
}
